package redbook;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.robot.common.utils.RedBookSignatureUtil.buildSignature;


public class RedBookCaller {
    private static final String API_URL = "https://edith.xiaohongshu.com/api/sns/v1/ext/access/token";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String getAccessToken(String nonce,long timestamp,String appKey) throws Exception {
        String appSecret = "e9529a757286c386b2f1f6a8ed3c1732";
//        String appSecret = "f4124f0dc19816e9455dbe78dbd7059f";

        String signature = buildSignature( nonce, timestamp+"",appSecret, appKey);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("app_key", appKey);
        requestBody.put("nonce", nonce);
        requestBody.put("timestamp", timestamp);
        requestBody.put("signature", signature);
        // 设置 expires_in 为 24 小时后的时间戳
        requestBody.put("expires_in", timestamp + 24 * 60 * 60 * 1000);

        try {
            return sendPostRequest(API_URL, requestBody);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }



    private static String generateSignature(String appKey, String nonce, long timestamp, String appSecret) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("appKey=").append(appKey)
                .append("&nonce=").append(nonce)
                .append("&timestamp=").append(timestamp)
                .append("&appSecret=").append(appSecret);
        return sha256(stringBuilder.toString());
    }

    private static String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String sendPostRequest(String url, Map<String, Object> requestBody) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");

        StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody), ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity!= null) {
                return EntityUtils.toString(responseEntity);
            }
        }
        return null;
    }
}